<?php
/**
 * 医生管理
 * Created by PhpStorm.
 * User: dower
 * Date: 2016/7/26 0026
 * Time: 下午 15:31
 */
namespace Web\Model\Doctor;
use Think\Model;
use Think\Page;

class DoctorModel extends Model
{

    /**
     * 得到诊疗分页数据(患者去重)
     * @param array $where
     * @param int $size
     * @return array
     */
    public function patientList($where = array(),$size=10){
        //得到分页信息
        $count = M('DoctorTreatment')->alias('a')->where($where)->join(' JOIN __PATIENT__ b on a.patient_id=b.id')->count('distinct(a.patient_id)');//去重统计
        $pageTool = new Page($count, $size);
        //设置分页信息
        $page_config = C('PAGE_CONFIG');
        foreach($page_config as $k=>$v){
            $pageTool->setConfig($k,$v);
        }
        $pageHtml = $pageTool->show();
        //得到表信息
        $first = $pageTool->firstRow;
        if ($first >= $count && $count != 0) {
            //超界则总是在最后一页,并且记录不能为0
            $first = $count - $size;
        }
        //查询数据(同时去重患者id)--分组内排序
        //得到子查询对象--先排序
        $query = M('DoctorTreatment')->order('date desc')->select(false);
        //执行分组
        $rows = $this->table($query.' a')->field("a.*,b.name")->group('a.patient_id')->where($where)->join(' JOIN __PATIENT__ b on a.patient_id=b.id')->order('CONVERT(b.name USING gbk) asc')->limit($first, $pageTool->listRows)->select();
        //返回结果
        return array('rows' => $rows, 'pageHtml' => $pageHtml,'count'=>$count);
    }

    /**
     * 得到我的患者-- 诊疗过或咨询过
     * @return mixed
     */
    public function myPatients(){
        $ids = array();
        $ids2 = array();
        //得到诊疗患者的id
        $apps = M('DoctorTreatment')->distinct(true)->where('doctor_id='.UID)->field('patient_id')->select();
        if($apps){
            $ids = array_column($apps,'patient_id');
        }
        //得到咨询医生的id
        $cons = M('DoctorConsult')->distinct(true)->where('doctor_id='.UID)->field('patient_id')->select();
        if($cons){
            $ids2 = array_column($cons,'patient_id');
        }
        //得到患者的ids
        $patient_ids = array_merge($ids,$ids2);
        //得到患者信息
        $rows = array();
        $count = 0;
        if($patient_ids){
            $patient_ids = array_unique($patient_ids);
            $rows = M('Patient')->alias('a')->field('a.id as pid,a.name')->where(array('a.id'=>array('in',$patient_ids)))->order('a.date desc')->select();
            if($rows){
                //得到最新的诊疗信息
                foreach ($rows as &$item){
                    $where = array('patient_id'=>$item['pid']);
                    $temp = M('DoctorTreatment')->where($where)->order('date desc')->find();
                    if($temp){
                        $item = array_merge($temp,$item);
                    }
                }
                unset($item);
                $count = count($rows);
            }
        }
        return array('rows'=>$rows,'count'=>$count);
    }

    /**
     * 得到诊疗分页数据(患者不去重)
     * @param array $where
     * @param int $size
     * @return array
     */
    public function treatmentlist($where = array(),$size=10){
        //得到分页信息
        $count = M('DoctorTreatment')->alias('a')->where($where)->join(' JOIN __PATIENT__ b on a.patient_id=b.id')->count();
        $pageTool = new Page($count, $size);
        //设置分页信息
        $page_config = C('PAGE_CONFIG');
        foreach($page_config as $k=>$v){
            $pageTool->setConfig($k,$v);
        }
        $pageHtml = $pageTool->show();
        //得到表信息
        $first = $pageTool->firstRow;
        if ($first >= $count && $count != 0) {
            //超界则总是在最后一页,并且记录不能为0
            $first = $count - $size;
        }
        //查询数据
        $rows = M('DoctorTreatment')->alias('a')->field("a.*,b.name,b.image as p_image,c.name as doctor")->where($where)->join(' JOIN __PATIENT__ b on a.patient_id=b.id JOIN __DOCTOR__ c on a.doctor_id=c.id')->order('a.treat_time desc')->limit($first, $pageTool->listRows)->select();
        //返回结果
        return array('rows' => $rows, 'count'=>$count, 'pageHtml' => $pageHtml);
    }

    /**
     * 添加患者
     * @param $requestData
     * @return bool|int false或id
     */
    public function addPatient($requestData){
        //没有账号添加账号, 有则更新信息, 然后添加诊疗信息
        if(empty($requestData['name'])) $requestData['name'] = $requestData['mobile'];//无姓名,默认为电话号码
        //验证该手机号是否存在
        $res = M('Patient')->field('id')->where('mobile='.$requestData['mobile'])->find();
        if($res){
            //更新患者信息
            M('patient')->where('mobile='.$requestData['mobile'])->save($requestData);
            $id = $res['id'];
        }else{
            //保存账户信息
            $requestData['family_id'] = get_unique_number();
            $requestData['password'] = think_ucenter_md5(C('DEFAULT_PASSWORD'), UC_AUTH_KEY);
            $id = M('patient')->add($requestData);
            if($id===false){
                $this->error = '创建账户失败';
                return false;
            }
            //添加环信
            $info = getHxUser($id,3);
            D('Huanxin')->createUser($info['username'],$info['password']);
        }
        //添加诊疗记录
        $requestData['doctor_id'] = UID;
        $requestData['patient_id'] = $id;
        if(empty($requestData['treat_time'])) $requestData['treat_time'] = date('Y-m-d');
        $rst =  M('DoctorTreatment')->add($requestData);
        if($rst===false){
            $this->error = '添加诊疗失败';
            return false;
        }else{
            return true;
        }
    }

    /**
     * 添加诊疗记录
     * @param $requestData
     * @return bool
     */
    public function addTreatment($requestData){
        $requestData['doctor_id'] = UID;
        $rst =  M('DoctorTreatment')->add($requestData);
        if($rst===false){
            $this->error = '添加诊疗失败';
            return false;
        }
        return true;
    }

    /**
     * 得到患者的诊疗列表
     * @param $where
     * @return array
     */
    public function patientTreatmentList($where){
        //得到表信息
        $rows = M('DoctorTreatment')->alias('a')->field('a.*,b.clinic_name as clinic,c.name as doctor')->order('a.treat_time desc')->where($where)->join(' JOIN __DOCTOR__ c on a.doctor_id=c.id JOIN __CLINIC__ b on c.clinic_id=b.id')->select();
        $count = 0;
        if($rows){
            $count = count($rows);
        }
        //返回结果
        return array('rows' => $rows,'count' => $count);
    }

    /**
     * 得到评价的列表
     * @param array $where
     * @param int $size
     * @return array
     */
    public function assessList($where=array(),$size=10){
        //得到分页信息
        $count = M('DoctorAssess')->alias('a')->where($where)->count();
        $pageTool = new Page($count, $size);
        //设置分页信息
        $page_config = C('PAGE_CONFIG');
        foreach($page_config as $k=>$v){
            $pageTool->setConfig($k,$v);
        }
        $pageHtml = $pageTool->show();
        //得到表信息
        $first = $pageTool->firstRow;
        if ($first >= $count && $count != 0) {
            //超界则总是在最后一页,并且记录不能为0
            $first = $count - $size;
        }
        //查询数据
        $rows = M('DoctorAssess')->alias('a')->field("a.*,b.name")->where($where)->join(' JOIN __PATIENT__ b on a.patient_id=b.id')->order('a.date desc')->limit($first, $pageTool->listRows)->select();
        //返回结果
        return array('rows' => $rows, 'pageHtml' => $pageHtml);
    }

    /**
     * 得到评价分析数据
     * @param array $where
     * @param int $type 1-总数,2-筛选
     * @param string $date 时间-年月
     * @return mixed
     */
    public function assessData($where=array(),$type=1,$date=''){
        //得到数据
        if($type==1){
            //得到总数
            $rst = M('DoctorAssess')->field('score')->where($where)->count();
            return $rst?$rst:0;
        }else{
            //得到具体某一月数据
            $date = $date?:date('Y-m');//默认为当前月
            //解析where
            if(is_array($where['doctor_id'])){
                $tt = implode(',',$where['doctor_id'][1]);
                $mywhere = " a.`doctor_id` in ({$tt})";
            }else{
                $mywhere = " a.`doctor_id`={$where['doctor_id']}";
            }
            $sql = "select a.*,b.name from __PREFIX__doctor_assess as a join __PREFIX__patient as b on a.patient_id=b.id  where {$mywhere} and DATE_FORMAT(a.`date`, '%Y-%m')='{$date}'";
            $rst = M('DoctorAssess')->query($sql);
            return $rst?$rst:array();
        }
    }

    /**
     * 得到咨询的列表
     * @param array $where
     * @return array
     */
    public function consultList($where=array()){
        //查询数据
        $rows = M('DoctorConsult')->alias('a')->field("a.*,b.name,b.image as p_image")->where($where)->join(' JOIN __PATIENT__ b on a.patient_id=b.id')->order('status,a.date desc')->select();
        //返回结果
        return array('rows' => $rows);
    }

    /**
     * 得到预约的列表
     * @param array $where
     * @return array
     */
    public function appointList($where=array()){
        //查询数据
        $rows = M('DoctorAppoint')->alias('a')->field("a.*,b.name,b.image as p_image")->where($where)->join(' JOIN __PATIENT__ b on a.patient_id=b.id')->order('status,a.time desc')->select();
        //返回结果
        return array('rows' => $rows);
    }

    /**
     * 得到疾病库的列表信息
     * @param $type
     * @return array
     */
    public function getCate($type){
        //得到一级分类信息
        $res = M('DiseaseCategary')->where('category='.$type)->select();
        if(!$res) return array();
        //得到二级元素
        $field = $type==0?'section_office_id':'crowd_id';
        foreach($res as &$item){
            $where[$field] = $item['id'];
            $temp = M('Disease')->field('id,disease_name')->where($where)->select();
            $item['children'] = $temp;
        }
        return $res;
    }

    /**
     * 得到名方的列表
     * @param array $where
     * @param int $size
     * @return array
     */
    public function recipeList($where=array(),$size=10){
        //得到分页信息
        $count = M('Prescription')->where($where)->count();
        $pageTool = new Page($count, $size);
        //设置分页信息
        $page_config = C('PAGE_CONFIG');
        foreach($page_config as $k=>$v){
            $pageTool->setConfig($k,$v);
        }
        $pageHtml = $pageTool->show();
        //得到表信息
        $first = $pageTool->firstRow;
        if ($first >= $count && $count != 0) {
            //超界则总是在最后一页,并且记录不能为0
            $first = $count - $size;
        }
        //查询数据
        $rows = M('Prescription')->where($where)->order('create_time desc')->limit($first, $pageTool->listRows)->select();
        //返回结果
        return array('rows' => $rows, 'pageHtml' => $pageHtml);
    }

    /**
     * 得到系统消息的列表
     * @param array $where
     * @param int $size
     * @return array
     */
    public function newsList($where=array(),$size=10){
        //得到分页信息
        $count = M('Prescription')->where($where)->count();
        $pageTool = new Page($count, $size);
        //设置分页信息
        $page_config = C('PAGE_CONFIG');
        foreach($page_config as $k=>$v){
            $pageTool->setConfig($k,$v);
        }
        $pageHtml = $pageTool->show();
        //得到表信息
        $first = $pageTool->firstRow;
        if ($first >= $count && $count != 0) {
            //超界则总是在最后一页,并且记录不能为0
            $first = $count - $size;
        }
        //查询数据
        $rows = M('SystemMessage')->where($where)->order('`date` desc')->limit($first, $pageTool->listRows)->select();
        //返回结果
        return array('rows' => $rows, 'pageHtml' => $pageHtml);
    }
}